package top.huhuiyu.springboot2.study.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.huhuiyu.springboot2.study.base.BaseDataResult;
import top.huhuiyu.springboot2.study.base.BaseResult;
import top.huhuiyu.springboot2.study.entity.TestEntity;
import top.huhuiyu.springboot2.study.exception.AppException;
import top.huhuiyu.springboot2.study.validate.CommonValidate;

import java.util.Optional;

/**
 * @author 胡辉煜
 * \@RestController = @Controller + @ResponseBody
 */
@Controller
public class IndexController {

  @RequestMapping("")
  @ResponseBody
  public BaseResult index() {
    return BaseResult.ok("欢迎使用后端接口");
  }

  @RequestMapping("/test/data")
  public String data(String name, Model model) {
    model.addAttribute("username", Optional.ofNullable(name).orElse("黑暗骑士"));
    model.addAttribute("list", new String[]{"a", "b", "c"});
    // 跳转到模板中的data.html
    return "data";
  }

  @RequestMapping("/test/exception")
  @ResponseBody
  public BaseResult exception(String message) {
    if (StringUtils.hasText(message)) {
      throw AppException.getInstance(message);
    }
    return BaseResult.ok("没有抛出异常");
  }

  @GetMapping("/test/exception2")
  @ResponseBody
  public BaseResult exception2(String age) {
    return BaseResult.ok("年龄：" + Integer.parseInt(age));
  }

  @PostMapping("/test/validate")
  @ResponseBody
  public BaseDataResult<TestEntity> validate(
      @RequestBody @Validated(CommonValidate.Add.class) TestEntity entity) {
    return BaseDataResult.ok(entity);
  }

  @PostMapping("/test/validate2")
  @ResponseBody
  public BaseDataResult<TestEntity> validate2(
      @RequestBody @Validated(CommonValidate.Update.class) TestEntity entity) {
    return BaseDataResult.ok(entity);
  }


}
